<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-polyfill</title>
</head>
<body>
    <script>
        const PENDING = 'pending';
        const SUCCESS = 'success';
        const ERROR = 'error';
        function MyPromise(fn){
            this.state = PENDING; // pending success error
            // this.fns = []; // functions[]
            this.successFn = [];
            this.errorFn = [];
            // reslove value
            this.successVal = null;
            // reject value
            this.errorVal = null;
            let reslove = (val) => {
                // console.log(val, this.successFn);
                if(this.state != PENDING){
                    return;
                }
                this.state = SUCCESS;
                this.successVal = val;
                this.successFn.map(fn => fn());
            };
            let reject = (val) => {
                if (this.state != PENDING) {
                    return;
                }
                this.state = ERROR;
                this.errorVal = val;
                this.errorFn.map(fn => fn());
            }
            try {
                fn(reslove, reject);
            } catch (error) {
                reject(error);
            }
        }
        MyPromise.prototype.then = function(onSuccess, onError){
            return new MyPromise((reslove, reject) => {
                if(this.state === SUCCESS){
                    let x = onSuccess(this.successVal);
                    reslove(x);
                }else if(this.state === ERROR){
                    let x = onError(this.errorVal);
                    reject(x);
                }else {
                    // PENDING
                    // console.log(1);
                    this.successFn.push(() => {
                        let x = onSuccess(this.successVal);
                        reslove(x);
                    });
                    this.errorFn.push(() => {
                        let x = onError(this.errorVal);
                        reject(x);
                    });
                }

            })
        }


        var a = function(){
            return new MyPromise(function(reslove, reject){
                setTimeout(() => {
                    reslove('success');
                }, 1000);
            });
        }
        a().then(res => {
            console.log(res);
            return 1;
        }).then(
            res => {
                console.log(res);
            }
        )
    </script>
</body>
</html>